import 'dart:math';

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'home_page.dart';

///执行动画
class AnimationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AnimationPage();
  // State<StatefulWidget> createState() => _TweenAnimation(); ///帧动画
  // State<StatefulWidget> createState() => _CustomPaintAnimation();//自定义绘制图形
  // State<StatefulWidget> createState() => _CustomCirclePaintAnimation(); //自定义绘制圆

}

///自定义绘制圆+颜色渐变
class _CustomCirclePaintAnimation extends State<AnimationPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController =
        new AnimationController(vsync: this, duration: Duration(seconds: 3));
    _animationController.addListener(_updateListener);
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        print("animation: completed...");
        // _animationController.reset();
      } else if (status == AnimationStatus.forward) {
        print("animation: forward...${_animationController.value}");
      } else if (status == AnimationStatus.dismissed) {
      } else if (status == AnimationStatus.reverse) {
        print("animation: reverse...");
        // _animationController.reset();
      }
    });
    _animationController.repeat(min: 0.1, max: 0.5, reverse: true);
    _animationController.forward();
  }

  _updateListener() {
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.amberAccent,
      child: CustomPaint(
        size: Size(300, 300),
        // painter: _CustomCircle(), ///绘制圆环
        // painter: _CustomPoint(), ///绘制点
        painter: _ShapePainter(
            color: Color.lerp(
                Colors.red, Colors.blue, _animationController.value)),
      ),
    );
  }
}

class _ShapePainter extends CustomPainter {
  final Color? color;
  var _paint = new Paint();

  _ShapePainter({this.color});

  @override
  void paint(Canvas canvas, Size size) {
    _paint.color = color ?? Colors.amber;
    canvas.drawCircle(
        Offset(size.width / 2, size.height / 2), size.width / 2, _paint);
  }

  @override
  bool shouldRepaint(covariant _ShapePainter oldDelegate) {
    // return color != oldDelegate.color;
    return true;
  }
}

///自定义动画
///CustomPaint：自定义画笔
class _CustomPaintAnimation extends State<AnimationPage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.amberAccent,
      child: CustomPaint(
        size: Size(300, 300),
        // painter: _CustomCircle(), ///绘制圆环
        // painter: _CustomPoint(), ///绘制点
        painter: _CustomPath(),

        ///绘制线
      ),
    );
  }
}

///绘制线
class _CustomPath extends CustomPainter {
  Paint _paint = new Paint()
    ..color = Colors.blue
    ..strokeWidth = 5
    ..style = PaintingStyle.stroke;

  ///stroke：绘制空心线；fill：实心线(默认)

  @override
  void paint(Canvas canvas, Size size) {
    var _path = new Path()
      ..moveTo(10, 10)
      ..lineTo(size.width - 10, 10)
      ..lineTo(size.width - 10, size.height / 2)
      ..close();
    canvas.drawPath(_path, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}

///绘制点
class _CustomPoint extends CustomPainter {
  Paint _paint = new Paint()
    ..color = Colors.red
    ..strokeWidth = 10
    ..strokeCap = StrokeCap.round;

  @override
  void paint(Canvas canvas, Size size) {
    var _points = [
      Offset(5, 5),
      Offset(size.width / 2, size.height / 2),
      Offset(size.width - 5, size.height - 5)
    ];

    ///points：绘制点；lines：绘制两个点之间的一段线(如果点数量是奇数，最后一个会被忽略)；polygon：把所有点都连起来
    canvas.drawPoints(PointMode.points, _points, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}

///自定义动画：变大变小的圆
class _CustomCircle extends CustomPainter {
  Paint _paint = new Paint()
    ..strokeWidth = 4
    ..style = PaintingStyle.fill
    ..isAntiAlias = false
    ..strokeCap = StrokeCap.round
    ..color = Colors.red;

  @override
  void paint(Canvas canvas, Size size) {
    print("width:${size.width}, height:${size.height}, pi:$pi");

    ///绘制圆
    // canvas.drawCircle(Offset(150, 150), 60, _paint);
    ///绘制椭圆
    // canvas.drawOval(Rect.fromLTWH(0, 0, size.width, size.height / 2), _paint);
    ///绘制圆弧
    // canvas.drawArc(Rect.fromLTRB(0, 0, size.width, size.height), 0, pi / 4, false, _paint);
    ///绘制圆角矩形
    canvas.drawRRect(
        RRect.fromLTRBR(10, 10, size.width - 10, size.height / 2,
            Radius.circular(size.height / 2)),
        _paint);
  }

  ///是否需要重绘，可以通过this != oldDelegate来判断
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

///帧动画
class _TweenAnimation extends State<AnimationPage>
    with SingleTickerProviderStateMixin {
  late Animation<double> _sizeTween;
  late AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
        duration: Duration(milliseconds: 2000), vsync: this);
    _sizeTween = new Tween(begin: 10.0, end: 300.0).animate(animationController)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          print("_sizeTween: completed...${_sizeTween.value}");
          setState(() {});
        } else if (status == AnimationStatus.forward) {
          print("_sizeTween: forward...${_sizeTween.value}");
        } else if (status == AnimationStatus.dismissed) {
          print("_sizeTween: dismissed...");
        } else if (status == AnimationStatus.reverse) {
          print("_sizeTween: reverse...");
        }
      });
    // _alphaTween = new Tween(begin: 0.0, end: 1.0).animate(animationController)..addStatusListener((status) {
    //   if (status == AnimationStatus.completed) {
    //     print("_alphaTween: completed...");
    //     setState(() {});
    //   } else if (status == AnimationStatus.forward) {
    //     print("_alphaTween: forward...");
    //   } else if (status == AnimationStatus.dismissed) {
    //     print("_alphaTween: dismissed...");
    //   } else if (status == AnimationStatus.reverse) {
    //     print("_alphaTween: reverse...");
    //   }
    // });
    animationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    print("size:${_sizeTween.value}, alpha:e}");
    return Opacity(
        opacity: 1.0,
        child: new Center(
          child: new Container(
            margin: new EdgeInsets.symmetric(vertical: 10.0),
            height: _sizeTween.value,
            width: _sizeTween.value,
            // child: InkWell(
            //   // onTap: () => {
            //   //   Navigator.push(context, CupertinoPageRoute(
            //   //     builder: (context) => HomePage(),
            //   //   ))
            //   // },
            //   child: new Text("haha"),
            // ),
            child: TextButton(
              onPressed: () => {
                Navigator.push(
                    context,
                    CupertinoPageRoute(
                      builder: (context) => HomePage(),
                    ))
              },
              child: new FlutterLogo(),
            ),
          ),
        ));
  }
}

///AnimationController：动画控制器，控制动画执行时间、开启、结束、重复等
///Animation：执行动画，动画执行速度，监听，记录值变化
class _AnimationPage extends State<AnimationPage>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController animationController;
  double size = 0.0;

  @override
  void initState() {
    super.initState();
    print("initState");
    animationController = new AnimationController(

      ///duration: Duration(milliseconds: 2000), lowerBound: 0.2, upperBound: 0.8, vsync: this
        duration: Duration(milliseconds: 2000),
        vsync: this);
    // animation = new Tween(begin: 0.0, end: 300.0).animate(animationController)
    //   ..addStatusListener((status) {
    //     setState(() {
    //       print("刷新...");
    //     });
    // });
    //linear：匀速；decelerate：匀减速；ease：先加速，后减速；easeIn：先慢，后快；easeOut：先快，后慢；easeInOut：先慢，然后加速，最后减速；
    animation = new CurvedAnimation(
        parent: animationController,
        curve: Curves.easeInOut,
        // curve: ShakeCurve(),
        reverseCurve: Curves.linear)
      ..addStatusListener((status) {
        ///监听动画执行状态
        if (status == AnimationStatus.completed) {
          print("state: completed...");
          animationController.reverse();
        } else if (status == AnimationStatus.forward) {
          print("state: forward...");
        } else if (status == AnimationStatus.dismissed) {
          print("state: dismissed...");
          animationController.forward();
        } else if (status == AnimationStatus.reverse) {
          print("state: reverse...");
        }
      })
    /*..addListener(() {
        setState(() {
          size = 300.0 * animation.value;
        });
        print(
            "addListener...${animation.value}, $size, ${animation.isCompleted}");
      })*/
    ;
    animationController.repeat(min: 0.5, max: 0.6);
    animationController.forward();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
    print("dispose");
  }

  @override
  Widget build(BuildContext context) {
    // return new Center(
    //   child: new Container(
    //     margin: new EdgeInsets.symmetric(vertical: 10.0),
    //     height: size,
    //     width: size,
    //     child: new FlutterLogo(),
    //   ),
    // );
    // return AnimationLogo(animation: animation);
    return AnimatedBuilder(
      animation: animation,
      builder: (BuildContext context, Widget? child) {
        double size = 300.0 * animation.value;
        return new Center(
          child: new Container(
            margin: new EdgeInsets.symmetric(vertical: 10.0),
            height: size,
            width: size,
            child: new FlutterLogo(),
          ),
        );
      },
    );
  }
}

///正弦曲线
class ShakeCurve extends Curve{

  @override
  double transform(double t) {
    return sin(t * 2 * pi);
  }
}

class AnimationLogo extends AnimatedWidget {
  AnimationLogo({
    Key? key,
    required Animation<double> animation,
  }) : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    Animation<double> animation = listenable as Animation<double>;
    double size = 300.0 * animation.value;
    return new Center(
      child: new Container(
        margin: new EdgeInsets.symmetric(vertical: 10.0),
        height: size,
        width: size,
        child: new FlutterLogo(),
      ),
    );
  }
}
